package com.kchouse.homepage;

import android.content.Intent;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.alibaba.fastjson.JSONObject;
import com.kchouse.MainActivity;
import com.kchouse.R;
import com.kchouse.bean.earnestDetail;
import com.kchouse.bean.quoteDetail;
import com.kchouse.bean.sheetDetail;
import com.kchouse.common.API;
import com.kchouse.common.BaseActivity;
import com.kchouse.common.MyHttpCycleContext;
import com.kchouse.common.ToastUtils;

import java.util.ArrayList;
import java.util.HashMap;

import cn.finalteam.okhttpfinal.BaseHttpRequestCallback;
import cn.finalteam.okhttpfinal.HttpRequest;
import cn.finalteam.okhttpfinal.RequestParams;

public class WorkorderDetailsActivity extends BaseActivity implements View.OnClickListener{

    private WorkorderDetailsActivity mContent;
    private Intent intent;
    private String id;
    private TextView tv_title;
    private ImageView iv_back;
    private TextView tv_ok;
    private TextView tv_userMobile;
    private TextView tv_carNumber;
    private TextView tv_totalHours;
    private TextView tv_totalParts;
    private TextView tv_quoteTime;
    private TextView tv_totalAll;
    private TextView tv_dealAll;
    private Double totalHours;
    private Double totalParts;
    private ArrayList<sheetDetail> list = new ArrayList<>();
    private ArrayList<sheetDetail> list1 = new ArrayList<>();
    private ArrayList<sheetDetail> list2 = new ArrayList<>();
    private ListView lv_item1;
    private ListView lv_item2;
    private LvAdapter adapter1;
    private LvAdapter2 adapter2;
//    private LvAdapter adapter1;
//    private LvAdapter2 adapter2;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_workorder_details);

        mContent = this;
        intiData();
        intiView();
    }

    private void intiView() {
        tv_title = (TextView) findViewById(R.id.tv_title);
        tv_title.setText("工单详情");
        iv_back = (ImageView) findViewById(R.id.iv_back);
        iv_back.setOnClickListener(this);
        tv_ok = (TextView) findViewById(R.id.tv_ok);
        tv_ok.setOnClickListener(this);


        tv_userMobile = (TextView) findViewById(R.id.tv_userMobile);
        tv_carNumber = (TextView) findViewById(R.id.tv_carNumber);
        tv_totalHours = (TextView) findViewById(R.id.tv_totalHours);
        tv_totalParts = (TextView) findViewById(R.id.tv_totalParts);
        tv_quoteTime = (TextView) findViewById(R.id.tv_quoteTime);
        tv_totalAll = (TextView) findViewById(R.id.tv_totalAll);
        tv_dealAll = (TextView) findViewById(R.id.tv_dealAll);

        lv_item1 = (ListView) findViewById(R.id.lv_item1);
        lv_item2 = (ListView) findViewById(R.id.lv_item2);
        adapter1 = new LvAdapter();
        lv_item1.setAdapter(adapter1);
        adapter2 = new LvAdapter2();
        lv_item2.setAdapter(adapter2);
    }

    private void intiData() {
        intent = getIntent();
        id = intent.getStringExtra("id");
        GetWorkorderdetails(id);
    }

    /**
     * 获取定金详情
     * @param id
     */
    private void GetWorkorderdetails(String id) {
        String url = API.GetWorkorderdetails + id;
        RequestParams params = new RequestParams(new MyHttpCycleContext());//请求参数
        params.addHeader("token", MainActivity.token);//添加header信息
        params.addFormDataPart("id", id);

        HttpRequest.get(url, params, new BaseHttpRequestCallback<String>() {

            //请求网络前
            @Override
            public void onStart() {
                showdialog();
            }

            @Override
            protected void onSuccess(String str) {
                Log.e("==", str);
                JSONObject json = JSONObject.parseObject(str);
                if (json.getBoolean("successful")) {
                    JSONObject datajson = JSONObject.parseObject(json.getString("data"));
                    JSONObject earnestjson = JSONObject.parseObject(datajson.getString("sheet"));

                    String status = earnestjson.getString("status");
                    if(status.equals("YES")){
                        tv_ok.setVisibility(View.GONE);
                    }else {
                        tv_ok.setVisibility(View.VISIBLE);
                    }
                    String userMobile = earnestjson.getString("userMobile");
                    tv_userMobile.setText("手机号：" + userMobile );
                    String carNumber = earnestjson.getString("carNumber");
                    tv_carNumber.setText("车牌号：" + carNumber);
                    totalHours = earnestjson.getDouble("totalHours");
                    tv_totalHours.setText("工时小计：" + totalHours + "元");
                    totalParts = earnestjson.getDouble("totalParts");
                    tv_totalParts.setText("配件小计：" + totalParts + "元");
                    String carTime = earnestjson.getString("carTime");
                    tv_quoteTime.setText("交车时间：" + carTime);
                    double toatlall = totalHours + totalParts;
                    tv_totalAll.setText("总计：" + toatlall + "元");


                    list.addAll(JSONObject.parseArray(earnestjson.getString("sheetDetailList"), sheetDetail.class));
                    for (int i = 0; i < list.size(); i++) {
                        sheetDetail item = list.get(i);
                        if (item.getType().equals("HOURS")) {
                            list1.add(item);
                        } else {
                            list2.add(item);
                        }
                    }
                    adapter1.notifyDataSetChanged();
                    adapter2.notifyDataSetChanged();
                } else {
                    String datastr = json.getString("data");
                    JSONObject data = JSONObject.parseObject(datastr);
                    ToastUtils.getInstanc(mContent).showToast(data.getString("msg"));
                }
            }

            //请求失败（服务返回非法JSON、服务器异常、网络异常）
            @Override
            public void onFailure(int errorCode, String msg) {
//                toast("网络异常~，请检查你的网络是否连接后再试");
                Log.e("==", msg);
            }

            //请求网络结束
            @Override
            public void onFinish() {
                dismissdialog();
            }
        });
    }


    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.iv_back:
                finish();
                break;
            case R.id.tv_ok:
                Postonfirmsheet();
                break;
        }
    }

    /**
     * 确认工单
     */
    private void Postonfirmsheet() {
        list.clear();
        String url = API.Postonfirmsheet+id;
        RequestParams params = new RequestParams(new MyHttpCycleContext());//请求参数
        params.addHeader("token", MainActivity.token);//添加header信息
        params.addFormDataPart("sheetId",id);
        HttpRequest.post(url, params, new BaseHttpRequestCallback<String>() {

            //请求网络前
            @Override
            public void onStart() {
                showdialog();
            }

            @Override
            protected void onSuccess(String str) {
                Log.e("==", str);
                JSONObject json = JSONObject.parseObject(str);
                if (json.getBoolean("successful")) {
                    String datastr = json.getString("data");
//                    JSONObject data = JSONObject.parseObject(datastr);
                    ToastUtils.getInstanc(mContent).showToast("已确认成功");
                    finish();
                } else {
                    String datastr = json.getString("data");
                    JSONObject data = JSONObject.parseObject(datastr);
                    ToastUtils.getInstanc(mContent).showToast(data.getString("msg"));
//                    if(data.getString("code").equals("401")||data.getString("code").equals("400"))
//                    {
//                        intent.setClass(mContent, LoginPhoneActivity.class);
//                        startActivity(intent);
//                        finish();
//                    }else {
//                        ToastUtils.getInstanc(mContent).showToast(data.getString("msg"));
//                    }
                }
            }

            //请求失败（服务返回非法JSON、服务器异常、网络异常）
            @Override
            public void onFailure(int errorCode, String msg) {
//                toast("网络异常~，请检查你的网络是否连接后再试");
                Log.e("==", msg);
            }

            //请求网络结束
            @Override
            public void onFinish() {
                dismissdialog();
            }

        });
    }


    class LvAdapter extends BaseAdapter {
        @Override
        public int getCount() {
            return list1.size();
        }

        @Override
        public Object getItem(int position) {
            return null;
        }

        @Override
        public long getItemId(int position) {
            return 0;
        }

        @Override
        public View getView(int position, View convertView, ViewGroup parent) {

            sheetDetail item = list1.get(position);
            View view = getLayoutInflater().inflate(R.layout.lv_manageline_item, null);
            TextView tv_detail = (TextView) view.findViewById(R.id.tv_detail);
            tv_detail.setText(item.getDetail());
            TextView tv_price = (TextView) view.findViewById(R.id.tv_price);
            tv_price.setText(item.getPrice() + "");
            TextView tv_num = (TextView) view.findViewById(R.id.tv_num);
            tv_num.setText(item.getNum() + "");
            TextView tv_total = (TextView) view.findViewById(R.id.tv_total);
            double toatl = item.getPrice() * item.getNum();
            tv_total.setText(toatl + "");
            RelativeLayout rl_1 = (RelativeLayout) view.findViewById(R.id.rl_1);
            rl_1.setVisibility(View.GONE);
//            TextView tv_item = (TextView) view.findViewById(R.id.tv_item);
//            tv_item.setOnClickListener(new OfferDetailsActivity.Lv1OnClick(item, tv_item));
            return view;
        }
    }



    class LvAdapter2 extends BaseAdapter {
        @Override
        public int getCount() {
            return list2.size();
        }

        @Override
        public Object getItem(int position) {
            return null;
        }

        @Override
        public long getItemId(int position) {
            return 0;
        }

        @Override
        public View getView(int position, View convertView, ViewGroup parent) {
            sheetDetail item = list2.get(position);
            View view = getLayoutInflater().inflate(R.layout.lv_manageline_item, null);
            TextView tv_detail = (TextView) view.findViewById(R.id.tv_detail);
            tv_detail.setText(item.getDetail());
            TextView tv_price = (TextView) view.findViewById(R.id.tv_price);
            tv_price.setText(item.getPrice() + "");
            TextView tv_num = (TextView) view.findViewById(R.id.tv_num);
            tv_num.setText(item.getNum() + "");
            TextView tv_total = (TextView) view.findViewById(R.id.tv_total);
            double toatl = item.getPrice() * item.getNum();
            tv_total.setText(toatl + "");
            RelativeLayout rl_1 = (RelativeLayout) view.findViewById(R.id.rl_1);
            rl_1.setVisibility(View.GONE);
//            TextView tv_item = (TextView) view.findViewById(R.id.tv_item);
//            tv_item.setOnClickListener(new Lv2OnClick(item, tv_item));
            return view;
        }
    }

}
